<template>
  <div class="quality-dashboard" v-loading="loading" element-loading-text="加载数据中...">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>质量数据看板</h2>
    </div>
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stats-card">
        <div class="stats-content">
          <div class="stats-number">{{ statsData.overallQualifiedRate }}</div>
          <div class="stats-label">综合合格率</div>
          <!-- <div class="stats-trend" :class="statsData.overallQualifiedTrendDirection">
            {{ statsData.overallQualifiedTrendDirection === 'up' ? '↑' : '↓' }} {{ statsData.overallQualifiedTrend }}
          </div> -->
        </div>
        <div class="stats-icon blue">
          <el-icon><TrendCharts /></el-icon>
        </div>
      </div>
      
      <div class="stats-card">
        <div class="stats-content">
          <div class="stats-number">{{ statsData.monthlyExceptionCount }}</div>
          <div class="stats-label">本月异常次数</div>
          <!-- <div class="stats-trend" :class="statsData.monthlyExceptionTrendDirection">
            {{ statsData.monthlyExceptionTrendDirection === 'up' ? '↑' : '↓' }} {{ statsData.monthlyExceptionTrend }}
          </div> -->
        </div>
        <div class="stats-icon green">
          <el-icon><Document /></el-icon>
        </div>
      </div>
      
      <div class="stats-card">
        <div class="stats-content">
          <div class="stats-number">{{ statsData.topDefectSupplier }}</div>
          <div class="stats-label">供应商 TOP1 缺陷率</div>
          <div class="stats-number">{{ statsData.topDefectRate }}</div>
          <!-- <div class="stats-trend" :class="statsData.topDefectTrendDirection">
            {{ statsData.topDefectTrendDirection === 'up' ? '↑' : '↓' }} {{ statsData.topDefectTrend }}
          </div> -->
        </div>
        <div class="stats-icon orange">
          <el-icon><Warning /></el-icon>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 原材料合格率趋势 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>原材料合格率趋势</h3>
          <div class="chart-controls">
            <el-checkbox v-model="showComparison">同期对比</el-checkbox>
            <el-button size="small" @click="downloadChart">下载图表</el-button>
          </div>
        </div>
        <div ref="materialChart" class="chart-container" v-loading="!materialChartInstance"></div>
      </div>

      <!-- 缺陷分析 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>缺陷分析</h3>
        </div>
        <div ref="defectChart" class="chart-container" v-loading="!defectChartInstance"></div>
      </div>
    </div>

    <!-- 第二行图表 -->
    <div class="charts-section">
      <!-- 半成品合格率趋势 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>半成品合格率趋势</h3>
          <div class="chart-controls">
            <el-checkbox v-model="showSemiComparison">同期对比</el-checkbox>
            <el-button size="small" @click="downloadSemiChart">下载图表</el-button>
          </div>
        </div>
        <div ref="semiProductChart" class="chart-container" v-loading="!semiProductChartInstance"></div>
      </div>

      <!-- 成品合格率趋势 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>成品合格率趋势</h3>
          <div class="chart-controls">
            <el-checkbox v-model="showFinalComparison">同期对比</el-checkbox>
            <el-button size="small" @click="downloadFinalChart">下载图表</el-button>
          </div>
        </div>
        <div ref="finalProductChart" class="chart-container" v-loading="!finalProductChartInstance"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { Search, TrendCharts, Document, Warning } from '@element-plus/icons-vue'
//import { getQualityDashboardService } from '@/api/QualityManagerApi'
import { ElMessage } from 'element-plus'

// 筛选表单
const filterForm = ref({
  dateRange: ['2023-12-01', '2023-12-31'],
  inspectionType: '', // 质检类型：原材料、半成品、成品
  supplier: '',
  defectType: '' // 保留缺陷类型
})

// 统计数据
const statsData = ref({
  overallQualifiedRate: '95.7%',
  overallQualifiedTrend: '1.5%',
  overallQualifiedTrendDirection: 'up',
  monthlyExceptionCount: 27,
  monthlyExceptionTrend: '8.5%',
  monthlyExceptionTrendDirection: 'up',
  topDefectSupplier: '深圳光电科技有限公司',
  topDefectRate: '2.2%',
  topDefectTrend: '0.5%',
  topDefectTrendDirection: 'down'
})

// 图表控制
const showComparison = ref(false)
const showSemiComparison = ref(false)
const showFinalComparison = ref(false)

// 图表引用
const materialChart = ref()
const defectChart = ref()
const semiProductChart = ref()
const finalProductChart = ref()

// 图表实例
let materialChartInstance: echarts.ECharts | null = null
let defectChartInstance: echarts.ECharts | null = null
let semiProductChartInstance: echarts.ECharts | null = null
let finalProductChartInstance: echarts.ECharts | null = null

// 图表数据
const materialData = ref({
  dates: ['12-01', '12-02', '12-03', '12-04', '12-05', '12-06', '12-07', '12-08', '12-09'],
  qualified: [100, 98, 99, 98, 99, 98, 100, 99, 98],
  unqualified: [0, 2, 1, 2, 1, 2, 0, 1, 2]
})

const defectData = ref([
  { name: 'LED灯芯缺陷', value: 8 },
  { name: '固晶', value: 6 },
  { name: '焊线', value: 5 },
  { name: '点粉', value: 4 },
  { name: '封装', value: 3 },
  { name: '光通量', value: 2 },
  { name: '色温', value: 1 },
  { name: '显色指数', value: 1 },
  { name: '老化指数', value: 1 }
])

const semiProductData = ref({
  dates: ['12-01', '12-02', '12-03', '12-04', '12-05', '12-06', '12-07', '12-08', '12-09'],
  qualified: [98, 99, 98, 99, 98, 99, 98, 99, 98],
  unqualified: [2, 1, 2, 1, 2, 1, 2, 1, 2]
})

const finalProductData = ref({
  dates: ['12-01', '12-02', '12-03', '12-04', '12-05', '12-06', '12-07', '12-08', '12-09'],
  qualified: [98, 99, 98, 99, 98, 99, 98, 99, 98],
  unqualified: [2, 1, 2, 1, 2, 1, 2, 1, 2]
})

// 加载状态
const loading = ref(false)

// 初始化原材料合格率图表
const initMaterialChart = async () => {
  await nextTick()
  if (materialChart.value) {
    materialChartInstance = echarts.init(materialChart.value)
    const option = {
      title: {
        text: 'LED灯珠尺寸',
        left: 'center',
        bottom: 10,
        textStyle: {
          fontSize: 12,
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['合格', '不合格'],
        top: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: materialData.value.dates,
        axisLabel: {
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value}%',
          fontSize: 10
        }
      },
      series: [
        {
          name: '合格',
          type: 'line',
          data: materialData.value.qualified,
          smooth: true,
          lineStyle: {
            color: '#1890ff'
          },
          itemStyle: {
            color: '#1890ff'
          }
        },
        {
          name: '不合格',
          type: 'line',
          data: materialData.value.unqualified,
          smooth: true,
          lineStyle: {
            color: '#ff4d4f'
          },
          itemStyle: {
            color: '#ff4d4f'
          }
        }
      ]
    }
    materialChartInstance.setOption(option)
  }
}

// 初始化缺陷分析图表
const initDefectChart = async () => {
  await nextTick()
  if (defectChart.value) {
    defectChartInstance = echarts.init(defectChart.value)
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        textStyle: {
          fontSize: 12
        }
      },
      series: [
        {
          name: '缺陷类型',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: defectData.value.map((item, index) => ({
            ...item,
            itemStyle: {
              color: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff'][index]
            }
          }))
        }
      ]
    }
    defectChartInstance.setOption(option)
  }
}

// 初始化半成品合格率图表
const initSemiProductChart = async () => {
  await nextTick()
  if (semiProductChart.value) {
    semiProductChartInstance = echarts.init(semiProductChart.value)
    const option = {
      title: {
        text: 'LED灯珠尺寸',
        left: 'center',
        bottom: 10,
        textStyle: {
          fontSize: 12,
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['焊接', '烧结', '点胶', '封装'],
        top: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: semiProductData.value.dates,
        axisLabel: {
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        min: 90,
        max: 100,
        axisLabel: {
          formatter: '{value}%',
          fontSize: 10
        }
      },
      series: [
        {
          name: '焊接',
          type: 'line',
          data: [98, 99, 98, 99, 98, 99, 98, 99, 98],
          smooth: true,
          lineStyle: { color: '#1890ff' },
          itemStyle: { color: '#1890ff' }
        },
        {
          name: '烧结',
          type: 'line',
          data: [97, 98, 97, 98, 97, 98, 97, 98, 97],
          smooth: true,
          lineStyle: { color: '#52c41a' },
          itemStyle: { color: '#52c41a' }
        },
        {
          name: '点胶',
          type: 'line',
          data: [96, 97, 96, 97, 96, 97, 96, 97, 96],
          smooth: true,
          lineStyle: { color: '#faad14' },
          itemStyle: { color: '#faad14' }
        },
        {
          name: '封装',
          type: 'line',
          data: [95, 96, 95, 96, 95, 96, 95, 96, 95],
          smooth: true,
          lineStyle: { color: '#f5222d' },
          itemStyle: { color: '#f5222d' }
        }
      ]
    }
    semiProductChartInstance.setOption(option)
  }
}

// 初始化成品合格率图表
const initFinalProductChart = async () => {
  await nextTick()
  if (finalProductChart.value) {
    finalProductChartInstance = echarts.init(finalProductChart.value)
    const option = {
      title: {
        text: '成品合格率',
        left: 'center',
        bottom: 10,
        textStyle: {
          fontSize: 12,
          color: '#666'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['试验', '色温', '光通量'],
        top: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: finalProductData.value.dates,
        axisLabel: {
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        min: 90,
        max: 100,
        axisLabel: {
          formatter: '{value}%',
          fontSize: 10
        }
      },
      series: [
        {
          name: '试验',
          type: 'line',
          data: [98, 99, 98, 99, 98, 99, 98, 99, 98],
          smooth: true,
          lineStyle: { color: '#1890ff' },
          itemStyle: { color: '#1890ff' }
        },
        {
          name: '色温',
          type: 'line',
          data: [97, 98, 97, 98, 97, 98, 97, 98, 97],
          smooth: true,
          lineStyle: { color: '#52c41a' },
          itemStyle: { color: '#52c41a' }
        },
        {
          name: '光通量',
          type: 'line',
          data: [96, 97, 96, 97, 96, 97, 96, 97, 96],
          smooth: true,
          lineStyle: { color: '#faad14' },
          itemStyle: { color: '#faad14' }
        }
      ]
    }
    finalProductChartInstance.setOption(option)
  }
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索条件:', filterForm.value)
  // 根据搜索条件重新加载数据
  //fetchDashboardData()
}

// 获取看板数据
/* const fetchDashboardData = async () => {
  loading.value = true
  try {
    const res = await getQualityDashboardService(filterForm.value)
    if (res.data.code === 1) {
      const data = res.data
      
      // 更新统计卡片数据
      if (data.stats) {
        // 处理综合合格率数据
        // 如果后端返回的是小数形式，转换为百分比格式
        let overallRate = data.stats.overallQualifiedRate || '98.7%';
        // 如果是数字类型，转换为百分比字符串
        if (typeof overallRate === 'number') {
          overallRate = (overallRate * 100).toFixed(1) + '%';
        }
        
        statsData.value = {
          overallQualifiedRate: overallRate,
          overallQualifiedTrend: data.stats.overallQualifiedTrend || '2%',
          overallQualifiedTrendDirection: data.stats.overallQualifiedTrendDirection || 'up',
          monthlyExceptionCount: data.stats.monthlyExceptionCount || 127,
          monthlyExceptionTrend: data.stats.monthlyExceptionTrend || '12.5%',
          monthlyExceptionTrendDirection: data.stats.monthlyExceptionTrendDirection || 'up',
          topDefectSupplier: data.stats.topDefectSupplier || '深圳光电科技有限公司',
          topDefectRate: data.stats.topDefectRate || '2.8%',
          topDefectTrend: data.stats.topDefectTrend || '0.9%',
          topDefectTrendDirection: data.stats.topDefectTrendDirection || 'down'
        }
      }
      
      // 更新图表数据
      if (data.materialData) {
        materialData.value = data.materialData
        if (materialChartInstance) {
          materialChartInstance.setOption({
            xAxis: { data: materialData.value.dates },
            series: [
              { data: materialData.value.qualified },
              { data: materialData.value.unqualified }
            ]
          })
        }
      }
      
      if (data.defectData) {
        defectData.value = data.defectData
        if (defectChartInstance) {
          defectChartInstance.setOption({
            series: [{
              data: defectData.value.map((item, index) => ({
                ...item,
                itemStyle: {
                  color: ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff'][index % 7]
                }
              }))
            }]
          })
        }
      }
      
      if (data.semiProductData) {
        semiProductData.value = data.semiProductData
        if (semiProductChartInstance) {
          semiProductChartInstance.setOption({
            xAxis: { data: semiProductData.value.dates },
            series: [
              { data: semiProductData.value.qualified },
              { data: semiProductData.value.unqualified }
            ]
          })
        }
      }
      
      if (data.finalProductData) {
        finalProductData.value = data.finalProductData
        if (finalProductChartInstance) {
          finalProductChartInstance.setOption({
            xAxis: { data: finalProductData.value.dates },
            series: [
              { data: finalProductData.value.qualified },
              { data: finalProductData.value.unqualified }
            ]
          })
        }
      }
      
      ElMessage.success('数据加载成功')
    }
  } catch (error) {
    console.error('获取看板数据出错:', error)
    ElMessage.error('获取数据出错，请稍后重试')
  } finally {
    loading.value = false
  }
} */

// 下载图表
const downloadChart = () => {
  if (materialChartInstance) {
    const url = materialChartInstance.getDataURL({
      type: 'png',
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = url
    link.download = '原材料合格率趋势.png'
    link.click()
  }
}

const downloadSemiChart = () => {
  if (semiProductChartInstance) {
    const url = semiProductChartInstance.getDataURL({
      type: 'png',
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = url
    link.download = '半成品合格率趋势.png'
    link.click()
  }
}

const downloadFinalChart = () => {
  if (finalProductChartInstance) {
    const url = finalProductChartInstance.getDataURL({
      type: 'png',
      backgroundColor: '#fff'
    })
    const link = document.createElement('a')
    link.href = url
    link.download = '成品合格率趋势.png'
    link.click()
  }
}

// 组件挂载后初始化图表并加载数据
onMounted(async () => {
  await Promise.all([
    initMaterialChart(),
    initDefectChart(),
    initSemiProductChart(),
    initFinalProductChart()
  ])
  
  // 加载后端数据
  //fetchDashboardData()
})
</script>

<style lang="scss" scoped>
.quality-dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 140px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    
    h2 {
      margin: 0;
      color: #fff;
      font-size: 28px;
      font-weight: bold;
    }
  }

  .filter-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;

    .stats-card {
      background: white;
      padding: 24px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: space-between;
      align-items: center;

      .stats-content {
        .stats-number {
          font-size: 32px;
          font-weight: bold;
          color: #333;
          margin-bottom: 8px;
        }

        .stats-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
        }

        .stats-trend {
          font-size: 12px;
          font-weight: 500;
          
          &.up {
            color: #52c41a;
          }
          
          &.down {
            color: #f5222d;
          }
        }      
    }

    .stats-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;

      &.blue {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.green {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.orange {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.purple {
        background: linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%);
      }
    }
    }
  }

  .charts-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;

    .chart-card {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .chart-header {
        padding: 20px 20px 0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 16px;
          color: #333;
          font-weight: 500;
        }

        .chart-controls {
          display: flex;
          align-items: center;
          gap: 12px;
        }
      }

      .chart-container {
        height: 300px;
        padding: 20px;
      }
    }
  }
}
</style>